package com.hcrazy.manchester.app.controllers.comment;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hcrazy.manchester.app.pojo.ErrorMsg;
import com.hcrazy.manchester.app.pojo.Praise;
import com.hcrazy.manchester.app.pojo.User;
import com.hcrazy.manchester.app.services.PraiseService;
import com.hcrazy.manchester.app.utils.Constant;
import com.hcrazy.manchester.app.utils.Log;

/**
 * 点赞部分
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/api")
public class PraiseAPIController {
	
	@Autowired
	private PraiseService praiseService;
	
	/**
	 * 点赞
	 * @param 
	 * @return
	 */
	@RequestMapping(value="/praise",method={RequestMethod.POST,RequestMethod.GET},produces=MediaType.APPLICATION_JSON_VALUE)
	public @ResponseBody Object setPraise(
			HttpServletRequest req,
			@RequestParam long moduleId,
			@RequestParam int moduleType
			){
		try {
			//如果用户未登录，返回错误码
			Object obj = req.getSession().getAttribute("user");
			if(null == obj){
				return new ErrorMsg(Constant.MEMBER_LOGIN_NOT,"会员未登录，不允许点赞！");
			}
			User user = (User)obj;
			long userId = user.getUserId();
			
			Praise praise = new Praise();
			praise.setUserId(userId);
			praise.setModuleId(moduleId);
			praise.setModuleType(moduleType);
			
			return praiseService.addOrUpdatePraise(praise);
		} catch (Exception e) {
			Log.error(e.getMessage(), e);
			return new ErrorMsg(Constant.ERROR_CODE_SYSTEM_EXCEPTION,e.getMessage());
		}
	}
	
	/**
	 * 点赞数量
	 * @param 
	 * @return
	 */
	@RequestMapping(value="/praise/count",method={RequestMethod.POST,RequestMethod.GET},produces=MediaType.APPLICATION_JSON_VALUE)
	public @ResponseBody Object getPraiseCount(
			HttpServletRequest req,
			@RequestParam long moduleId,
			@RequestParam int moduleType
			){
		try {
			return praiseService.getCountByModule(moduleType, moduleId);
		} catch (Exception e) {
			Log.error(e.getMessage(), e);
			return new ErrorMsg(Constant.ERROR_CODE_SYSTEM_EXCEPTION,e.getMessage());
		}
	}
	
	/**
	 * 系统参数异常
	 * @param e
	 * @return
	 */
	@ExceptionHandler(Exception.class)
	public @ResponseBody ErrorMsg getException(Exception e){
		Log.error(e.getMessage(), e);
		return new ErrorMsg(Constant.ERROR_CODE_SYSTEM_EXCEPTION,e.getMessage());
	}
}
